/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.admin.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import lombok.AllArgsConstructor;

import javax.validation.Valid;

import org.apache.ibatis.annotations.Update;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.modules.admin.dto.WxFaultCauseDTO;
import org.springblade.modules.admin.vo.WxFaultTypeVO;
import org.springblade.modules.system.entity.Tenant;
import org.springblade.modules.system.service.ITenantService;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.modules.admin.entity.WxFaultCause;
import org.springblade.modules.admin.vo.WxFaultCauseVO;
import org.springblade.modules.admin.service.IWxFaultCauseService;
import org.springblade.core.boot.ctrl.BladeController;

import java.sql.Struct;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 维修原因表 控制器
 *
 * @author ysq
 * @since 2025-06-27
 */
@RestController
@AllArgsConstructor
@RequestMapping("admin/wx/fault/cause")
@Api(value = "故障原因配置", tags = "故障原因配置")
public class WxFaultCauseController extends BladeController {

	private final IWxFaultCauseService wxFaultCauseService;

	private final ITenantService tenantService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入wxFaultCause")
	public R<WxFaultCause> detail(Long id) {
		return R.data(wxFaultCauseService.detail(id));
	}


	/**
	 * 详情
	 */
	@GetMapping("/copy")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "拷贝", notes = "传入wxFaultCause")
	public R<Boolean> copy(Long id) {
		WxFaultCause serviceById = wxFaultCauseService.getById(id);
		if (serviceById.getIsOther() == 1) {
			throw new ServiceException("其它类型不能复制...");
		}
		serviceById.setSort(0);
		serviceById.setId(null);
		serviceById.setStatus(0);
		serviceById.setFaultName(serviceById.getFaultName() + "-副本");
		serviceById.setFromType(1);
		wxFaultCauseService.save(serviceById);
		List<WxFaultCause> list = wxFaultCauseService.list(Wrappers.<WxFaultCause>lambdaQuery().eq(WxFaultCause::getParentId, id));
		if (list.size() > 0) {
			list.forEach(o -> {
				o.setId(null);
				o.setFromType(1);
				o.setSort(0);
				o.setFaultName(o.getFaultName() + "-副本");
				o.setParentId(serviceById.getId());
			});
			wxFaultCauseService.saveBatch(list);
		}
		return R.data(true);
	}


	/**
	 * 自定义分页 维修原因表
	 */
	@PostMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入wxFaultCause")
	public R<IPage<WxFaultCause>> page(@RequestBody WxFaultCauseDTO wxFaultCause, @RequestBody Query query) {
		IPage<WxFaultCause> pages = wxFaultCauseService.selectWxFaultCausePage(Condition.getPage(query), wxFaultCause);
		return R.data(pages);
	}


	/**
	 * 新增或修改 维修原因表
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入wxFaultCause")
	public R submit(@Valid @RequestBody WxFaultCause wxFaultCause) {

		//校验序号不能相同
		if (wxFaultCause.getSort() != null) {
			List<WxFaultCause> wxFaultCauses = wxFaultCauseService.list(Wrappers.<WxFaultCause>lambdaQuery().eq(WxFaultCause::getSort, wxFaultCause.getSort()));
			List<WxFaultCause> causeList = wxFaultCauses.stream().filter(o -> !o.getId().equals(Convert.toLong(wxFaultCause.getId(),-1L))).collect(Collectors.toList());
			if (causeList.size() > 0) {
				throw new ServiceException("排序不能相同");
			}
		}

		if (wxFaultCause.getId() != null) {
			wxFaultCauseService.remove(Wrappers.<WxFaultCause>lambdaQuery().eq(WxFaultCause::getParentId, wxFaultCause.getId()));
		}
		List<WxFaultCause> childList = wxFaultCause.getChildList();

		//如果更新禁用 需要判断保留一条启用的
		if (wxFaultCause.getId() != null && wxFaultCause.getStatus() == 0) {
			List<WxFaultCause> list = wxFaultCauseService.list(Wrappers.<WxFaultCause>lambdaQuery().eq(WxFaultCause::getParentId, 0).eq(WxFaultCause::getStatus, 1).ne(WxFaultCause::getId, wxFaultCause.getId()));
			if (list.size() == 0) {
				throw new ServiceException("至少启用一个故障原因");
			}
		}

		//第一步校验 其它不能添加
		if (wxFaultCause.getId() == null) {
			if (JSON.toJSONString(wxFaultCause).contains("其它") || JSON.toJSONString(wxFaultCause).contains("其他")) {
				throw new ServiceException("故障原因[其它]名称不可重复");
			}
		}

		//第二步校验一级名称不能相同
		if (StrUtil.isNotEmpty(wxFaultCause.getFaultName())) {
			WxFaultCause serviceOne;
			if (wxFaultCause.getId() == null) {
				serviceOne = wxFaultCauseService.getOne(Wrappers.<WxFaultCause>lambdaQuery().eq(WxFaultCause::getFaultName, wxFaultCause.getFaultName()).eq(WxFaultCause::getParentId, 0).last("limit 1"));
			} else {
				serviceOne = wxFaultCauseService.getOne(Wrappers.<WxFaultCause>lambdaQuery().eq(WxFaultCause::getFaultName, wxFaultCause.getFaultName()).eq(WxFaultCause::getParentId, 0).ne(WxFaultCause::getId, wxFaultCause.getId()).last("limit 1"));
			}
			if (serviceOne != null) {
				throw new ServiceException("一级故障原因名称不能相同");
			}
		}

		//第三步校验二级名称不能相同
		if (childList != null && childList.size() > 0) {
			for (WxFaultCause wxFaultCause1 : childList) {
				if (StrUtil.isNotEmpty(wxFaultCause1.getFaultName())) {
					WxFaultCause serviceTwo;
					if (wxFaultCause1.getId() == null) {
						serviceTwo = wxFaultCauseService.getOne(Wrappers.<WxFaultCause>lambdaQuery().eq(WxFaultCause::getFaultName, wxFaultCause1.getFaultName()).ne(WxFaultCause::getParentId, 0).last("limit 1"));
					} else {
						serviceTwo = wxFaultCauseService.getOne(Wrappers.<WxFaultCause>lambdaQuery().eq(WxFaultCause::getFaultName, wxFaultCause1.getFaultName()).ne(WxFaultCause::getParentId, 0).ne(WxFaultCause::getId, wxFaultCause1.getId()).last("limit 1"));
					}
					if (serviceTwo != null) {
						throw new ServiceException("二级故障原因名称不能相同");
					}
				}
			}
		}

		//000000租户的逻辑
		String tenantId = AuthUtil.getTenantId();
		if (tenantId.equals("000000")) {
			return submitAdmin(wxFaultCause);
		}
		//普通租户的逻辑
		String nickName = AuthUtil.getNickName();
		wxFaultCause.setUserName(nickName);
		wxFaultCauseService.saveOrUpdate(wxFaultCause);
		if (childList != null && childList.size() > 0) {
			childList.forEach(o -> {
				o.setId(null);
				o.setParentId(wxFaultCause.getId());
				o.setUserName(nickName);
			});
			wxFaultCauseService.saveOrUpdateBatch(childList);
		}
		return R.status(true);
	}


	/**
	 * 000000租户的操作
	 *
	 * @param wxFaultCause
	 * @return
	 */
	private R submitAdmin(WxFaultCause wxFaultCause) {
		//先添加自己
		String nickName = AuthUtil.getNickName();
		wxFaultCause.setUserName(nickName);
		wxFaultCauseService.saveOrUpdate(wxFaultCause);
		List<WxFaultCause> childList = wxFaultCause.getChildList();
		if (childList != null && childList.size() > 0) {
			childList.forEach(o -> {
				o.setId(null);
				o.setParentId(wxFaultCause.getId());
				o.setUserName(nickName);
			});
			wxFaultCauseService.saveOrUpdateBatch(childList);
		}
		//同步給其他租戶
		if (wxFaultCause.getStatus() == 1) {
			List<String> tenantIds = tenantService.list().stream().map(Tenant::getTenantId).distinct().collect(Collectors.toList());
			tenantIds.remove("000000");
			tenantIds.clear();
			tenantIds.add("592800");
			for (String tenantId : tenantIds) {
				wxFaultCause.setId(null);
				wxFaultCauseService.saveTenantOne(tenantId, wxFaultCause);
			}
		}
		return R.status(true);
	}


	@GetMapping("list")
	public R<List<WxFaultCauseVO>> list() {
		return R.data(wxFaultCauseService.getTreeList());
	}


	@GetMapping("type/list")
	public R<List<WxFaultTypeVO>> typeList() {
		return R.data(wxFaultCauseService.getTypeList());
	}


	@GetMapping("update/status")
	public R<Boolean> update(Long id) {
		WxFaultCause wxFaultCause = wxFaultCauseService.getById(id);
		List<WxFaultCause> list = wxFaultCauseService.list(Wrappers.<WxFaultCause>lambdaQuery().eq(WxFaultCause::getParentId, id));
		if (list.size() == 0) {
			if (StrUtil.isEmpty(wxFaultCause.getFaultTypes())) {
				throw new ServiceException("故障原因必须关联责任");
			}
		} else {
			for (WxFaultCause wxFaultCause1 : list) {
				if (StrUtil.isEmpty(wxFaultCause1.getFaultTypes())) {
					throw new ServiceException("故障原因必须关联责任");
				}
			}
		}
		wxFaultCause.setStatus(1);
		wxFaultCauseService.updateById(wxFaultCause);
		String tenantId = AuthUtil.getTenantId();
		if (tenantId.equals("000000")) {
			wxFaultCause.setChildList(list);
			List<String> tenantIds = tenantService.list().stream().map(Tenant::getTenantId).distinct().collect(Collectors.toList());
			tenantIds.remove("000000");
			tenantIds.clear();
			tenantIds.add("592800");
			for (String tId : tenantIds) {
				wxFaultCause.setId(null);
				wxFaultCauseService.saveTenantOne(tId, wxFaultCause);
			}
		}
		return R.data(true);
	}


	@GetMapping("update/disStatus")
	public R<Boolean> updateDisStatus(Long id) {
		WxFaultCause wxFaultCause = wxFaultCauseService.getById(id);
		wxFaultCause.setStatus(0);
		wxFaultCauseService.updateById(wxFaultCause);
		return R.data(true);
	}
}
